import pygame
import random
import cv2
import mediapipe as mp

pygame.init()
# 初始化MediaPipe手势模块
mp_hands = mp.solutions.hands
hands = mp_hands.Hands(static_image_mode=False, max_num_hands=2, min_detection_confidence=0.5, min_tracking_confidence=0.5)

# 捕获视频帧
cap = cv2.VideoCapture(0)

# 设置屏幕尺寸
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))

# 设置游戏标题
pygame.display.set_caption('切水果游戏')

# 加载水果图片
fruit_images = {}
for fruit in ['apple', 'banana', 'cherry']:
    image_path = f'images/{fruit}.png'
    fruit_images[fruit] = pygame.image.load(image_path)

# 设置水果生成的位置范围
fruit_spawn_range = (100, screen_width - 100)

# 设置游戏时钟
clock = pygame.time.Clock()

# 初始化水果列表
fruits = []

# 水果落下的速度
fruit_speed = 5

# 游戏主循环
running = True
while running:
    # 检查事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 渲染背景
    screen.fill((255, 255, 255))

    # 从摄像头读取一帧图像
    ret, frame = cap.read()
    if not ret:
        break

    # 水平翻转图像，以便正像显示
    frame = cv2.flip(frame, 1)
    # 将图像从BGR转换为RGB，因为MediaPipe需要RGB图像
    image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

    # 进行手势检测
    results = hands.process(image)
    if results.multi_hand_landmarks:
        for hand_landmarks in results.multi_hand_landmarks:
            # 遍历每个手势关键点，并在图像上绘制
            for landmark in hand_landmarks.landmark:
                hand_x, hand_y = int(landmark.x * frame.shape[1]), int(landmark.y * frame.shape[0])
                pygame.draw.circle(screen, (0, 0, 255), (int(hand_x), int(hand_y)), 10)

    # 生成新的水果
    if random.randint(1, 100) < 10:  # 控制水果生成的频率
        fruit_type = random.choice(list(fruit_images.keys()))
        fruit_x = random.randint(*fruit_spawn_range)
        fruit_y = -fruit_images[fruit_type].get_height()  # 生成在屏幕上方
        fruits.append({'type': fruit_type, 'x': fruit_x, 'y': fruit_y, 'image': fruit_images[fruit_type]})

    # 更新水果位置
    for fruit in fruits[:]:
        screen.blit(fruit['image'], (fruit['x'], fruit['y']))

        fruit['y'] += fruit_speed
        if fruit['y'] > screen_height:
            fruits.remove(fruit)
        # 如果检测到手势
        elif results.multi_hand_landmarks:
            for hand_landmarks in results.multi_hand_landmarks:
                remove = False
                # 遍历每个手势关键点，并在图像上绘制
                for landmark in hand_landmarks.landmark:
                    hand_x, hand_y = int(landmark.x * frame.shape[1]), int(landmark.y * frame.shape[0])
                    if hand_x < fruit['x'] + fruit_images[fruit['type']].get_width() and \
                            hand_x + 50 > fruit['x'] and \
                            hand_y < fruit['y'] + fruit_images[fruit['type']].get_height() and \
                            hand_y + 50 > fruit['y']:
                        fruits.remove(fruit)
                        remove = True
                        break
                if remove:
                    break

    # 更新屏幕显示
    pygame.display.flip()

    # 控制游戏帧率
    clock.tick(60)

# 退出游戏
pygame.quit()
# 释放摄像头资源
cap.release()
cv2.destroyAllWindows()